#!/bin/bash

JAR_NAME="gift-server-core-1.0-SNAPSHOT.jar"
JAR_PATH="/home/admin/app/gift-server-core/target/$JAR_NAME"
LOG_DIR="/home/admin/app/logs"
LOG_PATH="$LOG_DIR/$(date +%F-%H%M)-gift-server.log"

# 创建日志目录（关键！）
mkdir -p "$LOG_DIR"

# 停止旧进程
PID=$(ps -ef | grep "$JAR_NAME" | grep -v grep | awk '{print $2}')
if [ -n "$PID" ]; then
  echo "Stopping old process $PID..."
  kill -9 $PID
else
  echo "No old process found."
fi

# 启动新进程
echo "Starting new jar: $JAR_NAME"
nohup java -jar "$JAR_PATH" > "$LOG_PATH" 2>&1 &

# 等待并确认是否启动成功
sleep 3
NEW_PID=$(ps -ef | grep "$JAR_NAME" | grep -v grep | awk '{print $2}')
if [ -n "$NEW_PID" ]; then
  echo "✅ Application started successfully, PID: $NEW_PID"
  echo "📄 Logs: $LOG_PATH"
else
  echo "❌ Failed to start application. Check if jar exists or inspect logs."
fi
